import 'dart:convert';

import 'package:bi_project/http/core/hi_error.dart';
import 'package:bi_project/http/core/hi_net.dart';
import 'package:bi_project/http/dao/login_dao.dart';
import 'package:bi_project/http/request/test_request.dart';
import 'package:bi_project/model/home_mo.dart';
import 'package:bi_project/navigator/bottom_navigator.dart';
import 'package:bi_project/navigator/hi_navigator.dart';
import 'package:bi_project/page/login_page.dart';
import 'package:bi_project/page/video_detail_page.dart';
import 'package:bi_project/utils/color.dart';
import 'package:bi_project/utils/toast.dart';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'db/hi_cache.dart';
import 'page/home_page.dart';
import 'page/registration_page.dart';

void main() {
  runApp(ScreenUtilInit(
    designSize: const Size(375, 2400),
    minTextAdapt: true,
    splitScreenMode: true,
    builder: (context, child) {
      return const BiliApp();
    },
  ));
}

class BiliApp extends StatefulWidget {
  const BiliApp({super.key});

  @override
  State<BiliApp> createState() => _BiliAppState();
}

class _BiliAppState extends State<BiliApp> {
  final BiliRouteDelegate _biliRouteDelegate = BiliRouteDelegate();
  // final BiliRouteInfomationParser _biliRouteInfomationParser =
  //     BiliRouteInfomationParser();

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: HiCache.preInit(),
        builder: (context, snapshot) {
          var widget = snapshot.connectionState == ConnectionState.done
              ? Router(
                  // routeInformationParser主要用于web,android,ios不需要
                  // routeInformationParser: _biliRouteInfomationParser,
                  routerDelegate: _biliRouteDelegate,
                  // routeInformationParser为null时可省略
                  // routeInformationProvider: PlatformRouteInformationProvider(
                  //     initialRouteInformation:
                  //         const RouteInformation(location: "/")),
                )
              : const Scaffold(
                  body: Center(
                    child: CircularProgressIndicator(),
                  ),
                );

          return MaterialApp(
            home: widget,
            theme: ThemeData(primarySwatch: white),
          );
        });
  }
}

class BiliRouteDelegate extends RouterDelegate<BiliRoutePath>
    with ChangeNotifier, PopNavigatorRouterDelegateMixin<BiliRoutePath> {
  @override
  final GlobalKey<NavigatorState> navigatorKey;

// 为navigator设置一个key，必要的时候可以通过navigatorKey.currentState来获取NavigatorState
  BiliRouteDelegate() : navigatorKey = GlobalKey<NavigatorState>() {
    // 实现路由跳转逻辑
    HiNavigator.getInstance().registerRouteJump(RouteJumpListener(
        onJumpTo: (RouteStatus routeStatus, {Map<dynamic, dynamic>? args}) {
      _routeStatus = routeStatus;
      if (routeStatus == RouteStatus.detail) {
        videoModel = args?["videoMo"];
      }
      notifyListeners();
    }));
  }

  List<MaterialPage> pages = [];

  VideoListMo? videoModel;

  // BiliRoutePath? path;

  RouteStatus _routeStatus = RouteStatus.home;

  RouteStatus get routeStatus {
    if (_routeStatus != RouteStatus.registration && !hasLogin) {
      return _routeStatus = RouteStatus.login;
    } else if (videoModel != null) {
      return _routeStatus = RouteStatus.detail;
    } else {
      return _routeStatus;
    }
  }

  bool get hasLogin => LoginDao.getBoardingPass() != null;

  @override
  Widget build(BuildContext context) {
    var index = getPageIndex(pages, routeStatus);
    List<MaterialPage> tempPage = pages;
    if (index > -1) {
      // 要打开的页面在栈中已存在，则将该页面和它上面所有的页面进行出栈
      // tip 具体要求根据需求而定，这里要求栈中只允许一个页面存在
      tempPage = tempPage.sublist(0, index);
    }
    var page;
    if (routeStatus == RouteStatus.home) {
      // 跳转首页所有清空，因为首页不可回退
      pages.clear();
      page = pageWrap(const BottomNavigator());
    } else if (routeStatus == RouteStatus.detail) {
      page = pageWrap(VideoDetailPage(videoModel!));
    } else if (routeStatus == RouteStatus.registration) {
      page = pageWrap(const RegistrationPage());
    } else if (routeStatus == RouteStatus.login) {
      page = pageWrap(const LoginPage());
    }
    tempPage = [...tempPage, page];

    // 通知路由页面发生变化
    HiNavigator.getInstance().notify(tempPage, pages);
    pages = tempPage;
    return WillPopScope(
      onWillPop: () async => !await navigatorKey.currentState!.maybePop(),
      child: Navigator(
        key: navigatorKey,
        pages: pages,
        onPopPage: (route, result) {
          if (route.settings is MaterialPage) {
            // 返回页未登录返回拦截
            if ((route.settings as MaterialPage).child is LoginPage) {
              if (!hasLogin) {
                showWarnToast("请先登录");
                return false;
              }
            }
          }
          // 在这里可以控制是否可以返回
          if (!route.didPop(result)) {
            return false;
          }
          var tempPage = [...pages];
          pages.removeLast();
          // 通知路由页面发生变化
          HiNavigator.getInstance().notify(pages, tempPage);
          return true;
        },
      ),
    );
  }

  @override
  Future<void> setNewRoutePath(BiliRoutePath path) async {
    // this.path = path;
  }
}

// class BiliRouteInfomationParser extends RouteInformationParser<BiliRoutePath> {
//   @override
//   Future<BiliRoutePath> parseRouteInformation(
//       RouteInformation routeInformation) async {
//     final url = Uri.parse(routeInformation.location!);
//     print("url:$url");
//     if (url.pathSegments.length == 0) {
//       return BiliRoutePath.home();
//     }
//     return BiliRoutePath.detail();
//   }
// }

// 定义路由数据，path
class BiliRoutePath {
  final String location;

  BiliRoutePath.home() : location = "/";

  BiliRoutePath.detail() : location = "/detail";
}
